/*
 * Created by SharpDevelop.
 * User: David
 * Date: 2006-11-29
 * Time: 23:56
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;

namespace tools
{
	/// <summary>
	/// Some useful utilities concerning parameterized Lists
	/// </summary>
	public class ListUtil
	{
		#region static methods
		
		/// <summary>
		/// Lets you swap two elements A and B in a parameterized List. What the list
		/// contains is not defined in the method, this is a template method. To swap
		/// elements in a List<int>, the user should state
		/// <code>ToolsResult result = Utilities.SwapElements<int>(MyIntList, pos1int, pos2int);</code>
		/// </summary>
		/// <param name="list">The List to swap elements in</param>
		/// <param name="pos1">The position of element A</param>
		/// <param name="pos2">The position of elemetn B</param>
		/// <returns>An object of ToolsResult, contianing info on the success/failure of the method</returns>
		public static ToolsResult SwapElements<T>(List<T> list, int pos1, int pos2)
		{
			ToolsResult result = new ToolsResult();
			
			if(pos1 >= list.Count)
			{
				result.m_Result = "pos1 out of range, larger than size of list";
				result.m_Failed = true;
			}
			
			if(pos1 < 0)
			{
				result.m_Result = "pos1 out of range, must be positive";
				result.m_Failed = true;
			}
			
			if(pos2 >= list.Count)
			{
				result.m_Result = "pos2 out of range, larger than size of list";
				result.m_Failed = true;
			}
			
			if(pos2 < 0)
			{
				result.m_Result = "pos2 out of range, must be positive";
				result.m_Failed = true;
			}
			
			if(!result.m_Failed)
			{
				if(pos1 > pos2)
				{
					int pos = pos1;
					pos1 = pos2;
					pos2 = pos;
				}
				
				T swap1 = list[pos1];
				T swap2 = list[pos2];
				
				list.RemoveAt(pos2);
				list.RemoveAt(pos1);
				
				list.Insert(pos1, swap2);
				list.Insert(pos2, swap1);
			}
			else
			{
				result.m_Header = "SwapElements<T> Error:";
			}
			
			return result;
		}
		
		/// <summary>
		/// Creates a copy of the passed List, if you remove objects from - or add objects to -
		/// this List copy, the original list will not be affected
		/// </summary>
		/// <param name="list">The List to copy</param>
		/// <returns>The copy of the List</returns>
		public static List<T> GetNoneReferencingCopyOfList<T>(List<T> list)
		{
			List<T> listCopy = new List<T>();
			
			if(list != null)
			{
				foreach(T it in list)
				{
					listCopy.Add(it);
				}
			}
			
			return listCopy;
		}
		
		#endregion
	}
}
